public class ChatActivity extends Activity implements ChatView {

    private List<Message> messageList = new ArrayList<>();
    private ChatAdapter adapter;
    private ListView listView;
    private ChatPresenter presenter;
    private ChatInput input;
    private VoiceSendingView voiceSendingView;
    private String identify;
    private RecorderUtil recorder = new RecorderUtil();
    private TIMConversationType type;
    private String titleStr;
    private SelectPicPopupWindow menuWindow;
    public static ChatActivity instance=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        //栈加入
		SysApplication.getInstance().addActivity(this);
        instance=this;
		//顶部颜色
        StatusBarCompat.setStatusBarColor(this, ColorUtil.Gray); 
		//键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        voiceSendingView = (VoiceSendingView) findViewById(R.id.voice_sending);
        listView = (ListView) findViewById(R.id.list);
        input = (ChatInput) findViewById(R.id.input_panel);
        identify = getIntent().getStringExtra("identify");
        type = (TIMConversationType) getIntent().getSerializableExtra("type");

        //音视频popwindow
        menuWindow = new SelectPicPopupWindow(ChatActivity.this, itemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
				@Override
				public void onDismiss() {
					setBackgroundAlpha(1.0f);
				}
			});
        input.setChatView(this);
        adapter = new ChatAdapter(this, R.layout.item_message, messageList);
        listView.setAdapter(adapter);
        listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        listView.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
						case MotionEvent.ACTION_DOWN:
							input.setInputMode(ChatInput.InputMode.NONE);
							break;
					}
					return false; //不消费
                }
			});
		//上拉到顶部获取更多
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
				private int firstItem;
				@Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
						presenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);
					}
				}
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
					firstItem = firstVisibleItem;
				}
			});
        registerForContextMenu(listView);
        initTitle();
        presenter = new ChatPresenter(this, identify, type);
        presenter.start();
    }

    //发送消息_照片_相册选择
    @Override
    public void sendImage() {
        ImagePicker.getInstance().setTitle("图片")
            .showCamera(false)
            .setMaxCount(9)
            .setImageLoader(new GlideLoader())
            .start(ChatActivity.this, ConUtil.College);
    }
    //发送消息_照片_相机拍照
    @Override
    public void sendPhoto() {
        askPermission();
    }
    //发送消息_收藏
    @Override
    public void sendCollection() {
        Intent intent=new Intent(ChatActivity.this, Wx_Sc.class);
        startActivity(intent);
    }
    //发送消息_名片
    @Override
    public void sendCard() {
		Intent intent=new Intent(ChatActivity.this, Wx_Mp.class);
		intent.putExtra("type","mp");
		startActivity(intent);
    }
    //发送消息_文字
    @Override
    public void sendText() {
        Message message = new TextMessage(input.getText());
        presenter.sendMessage(message.getMessage());
        input.setText("");
    }
    //发送消息_转账
    @Override
    public void sendMoney() {
		Intent intent=new Intent(ChatActivity.this, PayMoneyActivity.class);
		startActivityForResult(intent,ConUtil.PayMoney);     
    }
    //发送消息_红包
    @Override
    public void sendBuble() {
        Intent intent=new Intent(ChatActivity.this, PayBubleActivity.class);
        startActivityForResult(intent,ConUtil.PayBuble);       
    }
    //发送消息_动图
    @Override
    public void sendGif(String s){
        Message message = new MoneyMessage(s);
        presenter.sendMessage(message.getMessage());
    }
    //发送消息_开始发语音
    @Override
    public void startSendVoice() {
        voiceSendingView.setVisibility(View.VISIBLE);
        voiceSendingView.showRecording();
        recorder.startRecording();
    }
    //发送消息_结束发语音
    @Override
    public void endSendVoice() {
        voiceSendingView.release();
        voiceSendingView.setVisibility(View.GONE);
        recorder.stopRecording();
        if (recorder.getTimeInterval() >1&&recorder.getTimeInterval()<60) {
            Message message = new SoundMessage(recorder.getTimeInterval(), recorder.getFilePath());
            presenter.sendMessage(message.getMessage());
        } else{
            Toast.makeText(this, "录音时间请在1-60s内", Toast.LENGTH_SHORT).show();
        }    
    }
    //发送消息_位置
    @Override
    public void sendLocation(){
        Intent intent = new Intent(this, Wx_Location.class);
        startActivityForResult(intent, ConUtil.Location);
    }
    //发送消息_显示草稿
    @Override
    public void showDraft(TIMMessageDraft draft) {
        input.getText().append(TextMessage.getString(draft.getElems(), this));
    }
    //发送消息_音视频通话
    @Override
    public void videoAction() {
        setBackgroundAlpha(0.5f);
        menuWindow.showAtLocation(ChatActivity.this.findViewById(R.id.root), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置 
    }
    //发送消息_提示
    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    //Pause处理草稿
    @Override
    protected void onPause(){
        super.onPause();
        if (input.getText().length() > 0){
            TextMessage message = new TextMessage(input.getText());
            presenter.saveDraft(message.getMessage());
        }else{
            presenter.saveDraft(null);
        }
        presenter.readMessages();
        MediaUtil.getInstance().stop();
    }

    //Destroy处理
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    //显示单个
    @Override
    public void showMessage(TIMMessage message) {
        try{
            if (message == null) {
                adapter.notifyDataSetChanged();
            } else {
                Message mMessage = MessageFactory.getMessage(message);
                if (mMessage != null) {
                    if (messageList.size()==0){
						mMessage.setHasTime(null);
					}else{
						mMessage.setHasTime(messageList.get(messageList.size()-1).getMessage());
					}
					messageList.add(mMessage);
					adapter.notifyDataSetChanged();
					listView.setSelection(adapter.getCount()-1);    
                }
            }
        }catch (Exception e){
        }
    }
    //显示列表
    @Override
    public void showMessage(List<TIMMessage> messages) {
        try{
            int falg= 0;
            for (int i = 0; i < messages.size(); ++i){
                Message mMessage = MessageFactory.getMessage(messages.get(i));
                if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted) continue;
                ++falg;
                if (i != messages.size() - 1){
                    mMessage.setHasTime(messages.get(i+1));
                }else{
                    mMessage.setHasTime(null);
                }
                messageList.add(0, mMessage);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(falg);
        }catch (Exception e){
        }
    }

    @Override
    public void showRevokeMessage(TIMMessageLocator timMessageLocator) {
        for (Message msg : messageList) {
            TIMMessageExt ext = new TIMMessageExt(msg.getMessage());
            if (ext.checkEquals(timMessageLocator)) {
                adapter.notifyDataSetChanged();
            }
        }
    }
    //清除所有消息
    @Override
    public void clearAllMessage() {
        messageList.clear();
    }
    //发送消息成功
    @Override
    public void onSendMessageSuccess(TIMMessage message) {
        showMessage(message);
    }
    //发送消息失败
    @Override
    public void onSendMessageFail(int code, String desc, TIMMessage message) {
        adapter.notifyDataSetChanged();
    }
    //重写-长按事件 
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Message message = messageList.get(info.position);
        menu.add(0, 1, Menu.NONE, "删除");
        if (message.isSendFail()){
            menu.add(0, 2, Menu.NONE, "重新发送");
        }else if (message.getMessage().isSelf()){
            menu.add(0, 3, Menu.NONE, "撤回");
        }
    }
    //重写-长按事件
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Message message = messageList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                message.remove();
                messageList.remove(info.position);
                adapter.notifyDataSetChanged();
                break;
            case 2:
                messageList.remove(message);
                presenter.sendMessage(message.getMessage());
                break;
            case 3:
                presenter.revokeMessage(message.getMessage());
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }
    //重写-Activity返回事件
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //相机拍照事件，又分为视频消息、照片消息
        if(requestCode == ConUtil.Camera){
            if(data.getStringExtra("v")!=null){
                    String path=data.getStringExtra("path");
                    if(data.getStringExtra("v").equals("picture")){
                        Message message = new PictureMessage(path,false);
                        presenter.sendMessage(message.getMessage());
                    }else {
                        String first=data.getStringExtra("video");
                        Message message = new VideoMessage(path,first,Long.parseLong("10000"));
                        presenter.sendMessage(message.getMessage());
                    }
            }
			//相册选择照片
        } else if(requestCode == ConUtil.College&& resultCode == RESULT_OK){
            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            for(String s:imagePaths){
				if(FileUtil.ifSizeSmall(s,1024*8)){
					Message message = new PictureMessage(path,false);
					presenter.sendMessage(message.getMessage());
				}else{
					Toast.makeText(this, "照片最大不能超过8m",Toast.LENGTH_SHORT).show();
				}
            }
			//定位消息
        } else if(requestCode==ConUtil.Location){
            if(data.getStringExtra("state")!=null){
                if(data.getStringExtra("state").equals("ok")&&data.getStringExtra("locat")!=null){
                    String locat=data.getStringExtra("locat");
                    Message message = new MoneyMessage(locat);
                    presenter.sendMessage(message.getMessage());
                }
            }
			//“收到红包”消息
        } else if(requestCode==ConUtil.ReBuble) {
            String danhao=data.getStringExtra("danhao");
            String qian=data.getStringExtra("qian");
            Message message = new MoneyMessage("amoneyhd#"+danhao+"@"+qian);
            presenter.sendMessage(message.getMessage());
			//“发送红包”消息
        }else if(requestCode==ConUtil.PayBuble){
            String qq=data.getStringExtra("money");
            if(!qq.equals("fail")){
                String danhao= MyMathUtil.getRandomString(5);
                Message message = new MoneyMessage("amoneyhb#"+danhao+"@"+qq);
                presenter.sendMessage(message.getMessage());
            }
			//“收到转账”消息
        }else if(requestCode==ConUtil.ReMoney){
            String zt=data.getStringExtra("zt");
            if(zt.equals("ok")){
                String danhao=data.getStringExtra("danhao");
                String qian=data.getStringExtra("qian");
                Message message = new MoneyMessage("amoneysd#"+danhao+"@"+qian);
                presenter.sendMessage(message.getMessage());
            }
			//“发送转账”消息
        }else if(requestCode==ConUtil.PayMoney){
            String qq=data.getStringExtra("money");
            if(！qq.equals("fail")){
                String danhao= MyMathUtil.getRandomString(5);
                Message message = new MoneyMessage("amoneyzz#"+danhao+"@"+qq);
                presenter.sendMessage(message.getMessage());
            }
        } 
    }

	//音视频点击事件
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.pop_video_btn01:
                    Intent intent=new Intent(ChatActivity.this,Wx_v_sp.class);
                    startActivity(intent);
                    break;
                case R.id.pop_video_btn02:
                    Intent intent2=new Intent(ChatActivity.this,Wx_v_yp.class);
                    startActivity(intent2);
                    break;
                default:
                    break;
            }
        }
    };
    //恢复背景色
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }
    //相机拍摄（摄像头+声音）权限去动态获取
    private void askPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if ( ContextCompat.checkSelfPermission(ChatActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED||
				ContextCompat.checkSelfPermission(ChatActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
				) {ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO}, 1);
			} else {
                Intent intent=new Intent(ChatActivity.this,Wx_Paishe.class);
                startActivityForResult(intent,ConUtil.Camera);
            }
        }else{
            Intent intent=new Intent(ChatActivity.this,Wx_Paishe.class);
            startActivityForResult(intent,ConUtil.Camera);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
					if(grantResults.length ==2 ){
						if(grantResults[0] == PackageManager.PERMISSION_GRANTED&&grantResults[1] == PackageManager.PERMISSION_GRANTED){
							Intent intent=new Intent(ChatActivity.this,Wx_Paishe.class);
							startActivityForResult(intet,ComUtil.Camera);
						}
					}
            default:
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //点击消息列表中照片后，展示大图
	//给传递两个数组:本地小图数组，大图url数组
    public void updateImageList(String uid){
        ArrayList<String> imagePathList = new ArrayList<>();
        ArrayList<String> imagePathListB = new ArrayList<>();
        for(int i=0;i<messageList.size();i++){
            Message message=messageList.get(i);
            if(message instanceof  ImageMessage){
                PictureMessage imageMessage=(PictureMessage)message;
                imagePathList.add(imageMessage.getSmallLocalPath());
                imagePathListB.add(imageMessage.getmUrl());
            }
        }
        Intent intent = new Intent(ChatActivity.this, ImageViewPagerActivity.class);
        int imagePosition=imagePathList.indexOf(uid);
        intent.putExtra("imagePosition",imagePosition);
        intent.putStringArrayListExtra("list",imagePathList);
        intent.putStringArrayListExtra("listB",imagePathListB);
        startActivity(intent);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void initTitle(){
        TemplateTitle title = (TemplateTitle) findViewById(R.id.chat_title);
        switch (type) {
            case C2C:
                title.setMoreImg(R.drawable.more_bk);
                if (FriendshipInfo.getInstance().isFriend(identify)){
                    title.setMoreImgAction(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								Intent intent = new Intent(ChatActivity.this, ProfileActivity.class);
								intent.putExtra("identify", identify);
								startActivity(intent);
							}
						});
                    FriendProfile profile = FriendshipInfo.getInstance().getProfile(identify);
                    title.setTitleText(titleStr = profile == null ? identify : profile.getName());
                    MyApplication.getInstance().setNow_name(titleStr = profile == null ? identify : profile.getName());
                }else{
                    title.setMoreImgAction(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								Intent person = new Intent(ChatActivity.this,AddFriendActivity.class);
								person.putExtra("id",identify);
								person.putExtra("name",identify);
								startActivity(person);
							}
						});
                    title.setTitleText(titleStr = identify);
                    MyApplication.getInstance().setNow_name(titleStr = identify);
                }
                break;
            case Group:
                title.setMoreImg(R.drawable.more_bk);
                title.setMoreImgAction(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(ChatActivity.this, Wx_group_de.class);
							intent.putExtra("identify", identify);
							startActivity(intent);
						}
					});
                title.setTitleText(GroupInfo.getInstance().getGroupName(identify)+"(12)");
                break;
        }
    }


}
